#!/bin/bash

# 设置UTF-8编码支持，确保中文正常显示
export LANG="zh_CN.UTF-8"
export LC_ALL="zh_CN.UTF-8"

# 启用严格模式
set -e

# 参数处理 - 是否同时构建ARM64镜像
BUILD_ARM64=false
if [ "$1" = "1" ]; then
    BUILD_ARM64=true
fi

# 初始化变量
IMAGE_NAME="mocatool"
IMAGE_VERSION="0.1.1"
X86_TAR_FILE="${IMAGE_NAME}-amd64.tar"
ARM64_TAR_FILE="${IMAGE_NAME}-arm64.tar"

echo -e "\033[32m======= EmbyTools多架构镜像构建脚本 =======\033[0m"
echo -e "\033[36m此脚本将构建X86和ARM64架构的Docker镜像并导出为tar文件\033[0m"
echo -e "\033[36m适用环境: Linux及其他支持Docker的系统\033[0m"

# 切换到脚本所在目录
echo -e "\033[33m切换到脚本所在目录...\033[0m"
cd "$(dirname "$0")"

# 检查Docker环境
echo -e "\n\033[33m检查Docker环境...\033[0m"
if command -v docker &> /dev/null; then
    DOCKER_VERSION=$(docker --version)
    echo -e "\033[32m✓ Docker已安装: $DOCKER_VERSION\033[0m"
else
    echo -e "\033[31m✗ 错误: 未找到Docker命令，请确保Docker已正确安装\033[0m"
    exit 1
fi

# 检查Buildx支持
echo -e "\n\033[33m检查Buildx支持...\033[0m"
if docker buildx version &> /dev/null; then
    echo -e "\033[32m✓ Buildx已安装\033[0m"
    
    # 创建并启用构建器
    docker buildx create --name multiarch-builder --use 2>/dev/null || true
    docker buildx use multiarch-builder
    
    # 启动构建器
    docker buildx inspect --bootstrap
else
    echo -e "\033[33m⚠ Buildx未安装，使用传统构建方式\033[0m"
fi

# 构建X86架构镜像
echo -e "\n\033[36m======= 构建X86架构镜像 =======\033[0m"
set +e  # 临时禁用错误退出
    echo -e "\033[33m开始构建X86架构镜像...\033[0m"
    docker build -t "${IMAGE_NAME}:${IMAGE_VERSION}-amd64" -t "${IMAGE_NAME}:latest-amd64" . --platform linux/amd64
    if [ $? -eq 0 ]; then
        echo -e "\033[32m✓ X86架构镜像构建成功\033[0m"
        
        # 导出X86镜像
        echo -e "\033[33m导出X86镜像到 $X86_TAR_FILE...\033[0m"
        docker save -o "$X86_TAR_FILE" "${IMAGE_NAME}:latest-amd64"
        if [ $? -eq 0 ]; then
            echo -e "\033[32m✓ X86镜像导出成功\033[0m"
        else
            echo -e "\033[31m✗ X86镜像导出失败\033[0m"
        fi
    else
        echo -e "\033[31m✗ X86架构镜像构建失败\033[0m"
    fi
set -e  # 重新启用错误退出

# 只有在构建ARM64时才执行ARM64镜像构建
if [ "$BUILD_ARM64" = true ]; then
    # 构建ARM64架构镜像
    echo -e "\n\033[36m======= 构建ARM64架构镜像 =======\033[0m"
    set +e  # 临时禁用错误退出
        # 检查并启用QEMU模拟器
        echo -e "\033[33m检查QEMU模拟器支持...\033[0m"
        docker run --rm --privileged multiarch/qemu-user-static --reset -p yes 2>/dev/null || true
        
        echo -e "\033[33m开始构建ARM64架构镜像...\033[0m"
        docker build -t "${IMAGE_NAME}:${IMAGE_VERSION}-arm64" -t "${IMAGE_NAME}:latest-arm64" . --platform linux/arm64
        if [ $? -eq 0 ]; then
            echo -e "\033[32m✓ ARM64架构镜像构建成功\033[0m"
            
            # 导出ARM64镜像
            echo -e "\033[33m导出ARM64镜像到 $ARM64_TAR_FILE...\033[0m"
            docker save -o "$ARM64_TAR_FILE" "${IMAGE_NAME}:latest-arm64"
            if [ $? -eq 0 ]; then
                echo -e "\033[32m✓ ARM64镜像导出成功\033[0m"
            else
                echo -e "\033[31m✗ ARM64镜像导出失败\033[0m"
            fi
        else
            echo -e "\033[31m✗ ARM64架构镜像构建失败\033[0m"
            echo -e "\033[33m提示: ARM64构建需要QEMU模拟器支持，或者在ARM设备上直接构建\033[0m"
        fi
    set -e  # 重新启用错误退出
fi

# 使用Buildx构建多架构镜像（推荐方式）
# 只有在构建ARM64时才执行Buildx多架构构建
if [ "$BUILD_ARM64" = true ]; then
    echo -e "\n\033[36m======= 使用Buildx构建多架构镜像 =======\033[0m"
    if docker buildx version &> /dev/null; then
        set +e
            echo -e "\033[33m开始使用Buildx构建多架构镜像...\033[0m"
            
            # 构建并推送多架构镜像
            # docker buildx build --platform linux/amd64,linux/arm64 \
            #     -t "${IMAGE_NAME}:${IMAGE_VERSION}" \
            #     -t "${IMAGE_NAME}:latest" \
            #     --push .
            
            echo -e "\033[33m注意: 多架构镜像推送需要Docker Hub账号，取消注释上面代码启用推送\033[0m"
            
            # 本地构建多架构镜像但不推送
            docker buildx build --platform linux/amd64,linux/arm64 \
                -t "${IMAGE_NAME}:multiarch" \
                --output type=docker,dest=- | docker load
                
            if [ $? -eq 0 ]; then
                echo -e "\033[32m✓ 多架构镜像构建成功\033[0m"
            else
                echo -e "\033[33m⚠ 多架构镜像构建失败，可忽略此错误\033[0m"
            fi
        set -e
    fi
fi

# 显示构建结果摘要
echo -e "\n\033[32m======= 构建结果摘要 =======\033[0m"
if [ -f "$X86_TAR_FILE" ]; then
    X86_SIZE=$(du -h "$X86_TAR_FILE" | cut -f1)
    echo -e "\033[32m✓ X86镜像文件: $X86_TAR_FILE ($X86_SIZE)\033[0m"
else
    echo -e "\033[31m✗ X86镜像文件不存在\033[0m"
fi

if [ -f "$ARM64_TAR_FILE" ]; then
    ARM64_SIZE=$(du -h "$ARM64_TAR_FILE" | cut -f1)
    echo -e "\033[32m✓ ARM64镜像文件: $ARM64_TAR_FILE ($ARM64_SIZE)\033[0m"
else
    echo -e "\033[31m✗ ARM64镜像文件不存在\033[0m"
fi

# 提供使用说明
echo -e "\n\033[36m======= 使用说明 =======\033[0m"
echo -e "\033[33m加载X86镜像: docker load -i ${X86_TAR_FILE}\033[0m"
echo -e "\033[33m加载ARM64镜像: docker load -i ${ARM64_TAR_FILE}\033[0m"
echo -e "\033[33m运行X86镜像: docker run --rm -p 8082:8082 ${IMAGE_NAME}:latest-amd64\033[0m"
echo -e "\033[33m运行ARM64镜像: docker run --rm -p 8082:8082 ${IMAGE_NAME}:latest-arm64\033[0m"
echo -e "\033[33m使用持久化数据卷: docker run --rm -p 8082:8082 -v embytools_data:/app/data -v embytools_config:/app/config ${IMAGE_NAME}:latest\033[0m"

# 环境使用提示
echo -e "\n\033[36m======= 环境说明 =======\033[0m"
echo -e "\033[33m1. 确保Docker已安装并运行\033[0m"
echo -e "\033[33m2. ARM64构建需要QEMU模拟器支持\033[0m"
echo -e "\033[33m3. 推荐使用Buildx进行多架构构建\033[0m"

echo -e "\n\033[32mEmbyTools镜像构建完成！\033[0m"

# 添加可执行权限提示
echo -e "\n\033[33m使用前请赋予脚本执行权限：\033[0m"
echo -e "chmod +x build-multi-arch.sh"
echo -e "\n\033[33m运行脚本（仅构建X86镜像）：\033[0m"
echo -e "./build-multi-arch.sh"
echo -e "\n\033[33m运行脚本（同时构建X86和ARM64镜像）：\033[0m"
echo -e "./build-multi-arch.sh 1"